package io.p2p.stream.turn.service;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.p2p.stream.turn.handler.TurnUdpServerHandler;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class TurnUdpServer {
    @Getter
    @Setter
    private String name;

    @Getter
    @Setter
    private String host;

    @Getter
    @Setter
    private int port;

    private final EventLoopGroup group;

    private final Bootstrap bootstrap;

    private Channel channel;

    public TurnUdpServer(String name, String host, int port){
        this.name = name;
        this.host = host;
        this.port = port;

        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new TurnUdpServerHandler());  // 添加自定义ChannelInitializer
    }

    public void start(CountDownLatch latch){
        try {
            channel = bootstrap.bind(host, port).sync().channel();
            log.info("Turn UDP Server started on ip: {}, port: {}", host, port);

            // 在 channel 关闭时释放资源
            channel.closeFuture().addListener(future -> {
                log.info("Turn UDP Server is shutting down...");
                shutdown();
                latch.countDown(); // 通知主线程一个服务已关闭
            });
        } catch (InterruptedException e) {
            log.error("Failed to start UDP Server: {}", e.getMessage());
        }
    }

    public void sendMsg(String msg,InetSocketAddress targetAddress){
        if(channel != null && channel.isOpen()) {
            channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                    msg, StandardCharsets.UTF_8), targetAddress));
        }else{
            throw new NullPointerException("Turn UDP Server Sender Channel is Null...");
        }
    }

    public void sendMsg(String msg,String targetHost,int targetPort){
        this.sendMsg(msg,new InetSocketAddress(targetHost,targetPort));
    }

    public void shutdown() {
        group.shutdownGracefully();
    }
}
